/**
 * @author 老刘
 * @desc 拍照
 */
import {
	haveAuth,
	openSetting,
	alert,
	showToastNoIcon,
	wxApi2Promise
} from '../../../utils/util';
import {processingPictures} from '../../../utils/compress_pictures_utils.js';
const app = getApp();
Page({
	data: {
		picPath: '/pages/canvas/assets/id_card_back_border.png', // 拍摄区域边框
		pic: '', // 图片url
		identifyResult: -1,// 上传结果 -1 未知 0成功 1失败
		pictureWidth: 0, // 压缩图片
		pictureHeight: 0,
		showLoading: false,
		showCamera: true
	},
	onLoad () {
		// 设置ios滑动上下部分背景
		wx.canIUse('setBackgroundColor') && wx.setBackgroundColor({
			backgroundColorBottom: '#33333C'
		});
	},
	async onShow () {
		this.setData({
			showCamera: true
		});
	},
	// 相机初始化失败
	async onCameraErrorHandle (e) {
		if (!await haveAuth(`scope.camera`)) {
			this.setData({
				showCamera: false
			});
			alert({
				content: '检查您未授权保存图片，请授权',
				showCancel: true,
				confirmText: '授权',
				confirm: async () => {
					await openSetting();
				}
			});
			return;
		}
		await openSetting();
		showToastNoIcon('相加初始化失败！');
	},
	// 从相册选择图片
	async choiceFromAbumHandle () {
		if (!this.data.showCamera) {
			await this.onCameraErrorHandle();
			return;
		}
		const info = await wxApi2Promise(wx.chooseImage, {
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album']
		}, this);
		this.setData({
			pic: info.tempFilePaths[0]
		});
		this.uploadFile();
	},
	// 拍照
	async takePhotoHandle () {
		if (!this.data.showCamera) {
			await this.onCameraErrorHandle();
			return;
		}
		const takePhoto = await wxApi2Promise(wx.createCameraContext().takePhoto, {
			quality: 'high'
		}, this);
		// ios手机拍照问题 ios手机拍照需要处理自己会旋转
		if (app.globalData.mobilePhoneSystem) {
			const imageInfo = await wxApi2Promise(wx.getImageInfo, {
				src: takePhoto.tempImagePath
			}, this);
			this.setData({
				showLoading: true
			});
			let canvasContext = wx.createCanvasContext('rotatingCanvas');
			let width = imageInfo.width;
			let height = imageInfo.height;
			this.setData({
				imageWidth: width,
				imageHeight: height
			});
			canvasContext.translate(width / 2, height / 2);
			canvasContext.rotate(0 * Math.PI / 180);
			canvasContext.drawImage(imageInfo.path, -width / 2, -height / 2, width, height);
			canvasContext.draw();
			this.drawImage();
		} else {
			this.setData({
				pic: takePhoto.tempImagePath
			});
			this.uploadFile();
		}
	},
	drawImage () {
		let that = this;
		setTimeout(async () => {
			// 将生成的canvas图片，转为真实图片
			const path = await wxApi2Promise(wx.canvasToTempFilePath, {
				x: 0,
				y: 0,
				canvasId: 'rotatingCanvas'
			}, this);
			that.setData({
				showLoading: false
			});
			that.setData({
				pic: path.tempFilePath
			});
			that.uploadFile();
		}, 400);
	},
	// 处理并上传图片
	uploadFile () {
		// 裁剪压缩图片
		processingPictures(this, this.data.pic, 'pressCanvas', 640, (res) => {
			let path = res ? res : this.data.pic;
			// 上传图片
			this.setData({
				showLoading: false,
				picPath: path
			});
		});
	}
});
